import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;




public class InstructionTable extends HashSet<Instruction> {
	
	private final HashSet<String> ALT_FORMAT_TABLE = new HashSet<String>(Arrays.asList("CLRA", "CLRX", "DMP", "HLT", "WDV", "RDV")); 
	private final HashSet<String> DIRECTIVE_TABLE = new HashSet<String>(Arrays.asList("STT", "RESET", "EQU", "EQUE", "ENT", "EXT", "END", "AEXS", "SKS", "CHC", "NUM", "ADC", "ADCE", "NOP")); 
	private final HashSet<String> NAME_TABLE = new HashSet<String>();
	InstructionTable(){
	}
	
	public void LoadInstructionTable(String table) {
		try {
			BufferedReader in = new BufferedReader(new FileReader(table));
		    String str = null;
		    String[] tokens;
			while ((str = in.readLine()) != null) {
				tokens = str.split(" ");
				Integer format = 0;
				if (tokens.length != 0) {
					if (tokens[3].equals("F1")) {
						format = 1;
					} else if (tokens[3].equals("F2")) {
						format = 2;
					} else if (tokens[3].equals("F3")) {
						format = 3;
					} else if (tokens[3].equals("F4")) {
						format = 4;
					} else if (tokens[3].equals("F5")) {
						format = 5;
					} else if (tokens[3].equals("F6")) {
						format = 6;
					} else if (tokens[3].equals("F7")) {
						format = 7;
					}
				}
				NAME_TABLE.add(tokens[0]);
				this.add(new Instruction(tokens[0], tokens[1], 1, format));
			}
			in.close();
		} catch (IOException e) {
		}
	}
	
	
	public boolean isInstruction(String inst){
		if (NAME_TABLE.contains(inst)){
			return true;
		}
		return false;
	}
	
	public String getInstruction (String opcode) {
		String instruction = null;
		for (Instruction i : this) {
			if (i.getOpcode().equals(opcode)) {
				instruction = i.getName();
			}
		}
		return instruction;
	}
	
	public boolean isDirective(String dir){
		if (DIRECTIVE_TABLE.contains(dir)){
			return true;
		}
		return false;
	}
	
	public boolean isAltFormat (String name) {
		if (ALT_FORMAT_TABLE.contains(name)) {
			return true;
		}
		return false;
	}

	public int findFormat (String name){
		for(Instruction i : this){
			if (i.getName().equals(name)){
				return i.getFormat();
			}
		}
		return 0;
	}
	
	public String findOpcode (String name) {
		for (Instruction i : this) {
			if (i.getName().equals(name)) {
				return i.getOpcode();
			}
		}
		return " ";
	}
}